import SwiftUI
import Alamofire

// Trade/fetchbooktrade
struct ResponseData_FetchBookTrade: Codable {
    let status: Bool
    let description: String
    let collection: [Trade]
}

class TradeBookTradeFetcher: ObservableObject {
    @Published var publishedResult: TradeCollection = TradeCollection(collection: [DefaultTrade])
    
    func fetch(bookId: String) {
        let requestURL = "http://62.234.45.120:1230/Trade/fetchbooktrade?bookId=" + bookId
        
        AF.request(requestURL, method: .get)
        .responseDecodable(of: ResponseData_FetchBookTrade.self) { response in
            if let responseData = response.value {
                if responseData.status {
                    self.publishedResult.collection = responseData.collection
                }
            }
        }
    }
}

// Trade/addtrade
struct RequestData_AddTrade: Codable {
    let userId: String
    let bookId: String
    let wantPrice: Int
    let location: String
    let comment: String
}

struct ResponseData_AddTrade: Codable {
    let status: Bool
    let description: String
}

class TradeAddTradeRequester: ObservableObject {
    @Published var requestStatus: RequestStatus = .ready
    @Published var publishedResult: Bool = false
    
    func request(userId: String, bookId: String, wantPrice: String, location: String, comment: String){
        // 准备数据
        let requestData = RequestData_AddTrade(userId: userId,
                                               bookId: bookId, 
                                               wantPrice: Int(Double(wantPrice[wantPrice.index(after: wantPrice.startIndex)..<wantPrice.endIndex])! * 100),
                                               location: location,
                                               comment: comment)
        
        // 准备URL
        let requestURL = "http://62.234.45.120:1230/Trade/addtrade"
        
        // 发起请求
        self.requestStatus = .requesting
        AF.request(requestURL,
                   method: .post,
                   parameters: requestData,
                   encoder: JSONParameterEncoder.default)
        .responseDecodable(of: ResponseData_AddTrade.self) { response in
            if let responseData = response.value {
                self.publishedResult = responseData.status
                self.requestStatus = .finish
            }
        }
    }
}
